package sql

import (
	"fmt"
	"gorm.io/driver/mysql"
	"gorm.io/driver/sqlite"
	"gorm.io/gorm"
	"log"
)

var GLOBAL_DB Database = Database{}

type Database struct {
	url      string
	username string
	password string
	Name     string
	Db       *gorm.DB
}

var database Database

func (d Database) CreateDbConnection(url, username, password, name, dbType string) Database {
	d.url = url
	d.username = username
	d.password = password
	d.Name = name
	switch dbType {
	case "mysql":
		{
			connectStr := fmt.Sprintf("%s:%s@tcp(%s)/%s?parseTime=True&loc=Local", d.username, d.password, d.url, d.Name)
			db, err := gorm.Open(mysql.Open(connectStr), &gorm.Config{})
			if err != nil {
				log.Printf("数据库连接失败，失败原因：%s", err.Error())
				return Database{}
			} else {
				d.Db = db
				return d
			}
		}
	case "local":
		connectStr := fmt.Sprintf("%s", d.url)
		db, err := gorm.Open(sqlite.Open(connectStr), &gorm.Config{})
		if err != nil {
			fmt.Println(err.Error())
			return Database{}
		} else {
			d.Db = db
			return d
		}
	default:
		{
			fmt.Println("错误的数据库类型")
			return Database{}
		}
	}
}
